package com.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.domain.ModelName;
import com.service.ModelNameService;

@Controller
@RequestMapping("/")
public class ModelNameController {
	@Autowired
	private ModelNameService modelNameService;
	
	@RequestMapping("showNames")
	public String showNames(ModelMap mm) {
		List<ModelName> nameList = modelNameService.getAllNames();

		mm.addAttribute("nameList",nameList);

		return "model/modelNameList";
	}
	@RequestMapping("saveModelName")
	public ModelAndView saveModelName(HttpServletRequest request,ModelName modelName){
		modelNameService.saveModelName(modelName);
		List<ModelName> nameList = modelNameService.getAllNames();
		
		return new ModelAndView("model/modelNameList","nameList",nameList);
	}

	@RequestMapping("modifyModelName")
	public ModelAndView modifyModelName(HttpServletRequest request,ModelName modelName){
		String oldName=request.getParameter("oldName");
		String newName=modelName.getModelName();
		modelNameService.updateModelName(oldName, newName);
		
		List<ModelName> nameList = modelNameService.getAllNames();
		return new ModelAndView("model/modelNameList","nameList",nameList);
	}
	@RequestMapping("delModelName")
	public ModelAndView delModelName(HttpServletRequest request,ModelName modelName){
		modelNameService.delModelName(modelName);
		
		List<ModelName> nameList = modelNameService.getAllNames();
		return new ModelAndView("model/modelNameList","nameList",nameList);
	}
	@RequestMapping("checkExist")
	public ModelAndView checkExist(HttpServletRequest request, HttpServletResponse response) {  
	    String modelName = request.getParameter("modelName");
	    ModelName model = new ModelName();
	    model.setModelName(modelName);
	    boolean flag = modelNameService.isExist(model);
		String checkResult=flag?"true":"false";
		String result = checkResult;
		
		response.setContentType("text/Xml;charset=gbk");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.println(result);

		} catch (IOException ex1) {
			ex1.printStackTrace();
		} finally {
			out.close();
		}
		return null;  
	}  
}
